$(function () {
    obj.init();
});

var obj = new JsFun();
function JsFun() {
    return {
        dataGrid: null,
        form: null,
        dom: {
            save: null,
            school: null
        },
        params: {
            mine: null,
            schools: null,
            iCIId:null
        },
        init: function () {
            this.params.mine = xhTool.getQuery('mine') || 0;
            this.params.iCIId = xhTool.getQuery('iCIId') || 0;
            this.dom.save   = $('#bt_form_add, #bt_form_edit');
            this.dom.school = $('#iSchoolId');

            this.dataGrid = new xhDataGrid($('#list'), 'Device/getRegister', {mine: this.params.mine,iCIId:this.params.iCIId});
            this.dataGrid.parseToolbar().init().activeButton(['bt_list_del', 'bt_list_done', 'bt_list_start_receive', 'bt_list_change_school', 'bt_list_syn','bt_list_returnTab', 'bt_list_bindLicence'],
                ['bt_list_repair', 'bt_list_history', 'bt_list_exchange']);
            this.funObj().bindDataGridEvent();

            this.form = new xhForm($('#xh_form'));
            this.form.parse().bindRequired(this.dom.save);

            this.dom.school.select2({
                width: 200
            });

            $('#bt_list_communication').menubutton({
                menu: '#menu_communication'
            });
            $('#bt_list_check').menubutton({
                menu: '#menu_check'
            });
            this.listener();
        },
        listener: function () {
            var $this = this;
            //添加分组按钮
            // $('#bt_list_group').menubutton({
            //     menu: '#menu_group'
            // });
            //查询
            xhTool.bindDocKeyDown(
                $('#bt_list_search').click(function () {
                    $this.funObj().searchList();
                })
            );
            //添加
            $('#bt_list_add').click(function () {
                $this.form.reset();
                xhExtra.forwardToForm(false);
                $('#iSource').val(1);
            });
            //删除
            $('#bt_list_del').click(function () {
                if (xhExtra.buttonDisabled($(this))) return false;
                $this.funObj().delRegister();
            });
            //标记使用完毕
            $('#bt_list_done').click(function () {
                if (xhExtra.buttonDisabled($(this))) return false;
                $this.funObj().doneRegister();
            });
            //添加
            $('#bt_form_add').click(function() {
                $this.form.submit(baseUrl + 'Device/createRegister', {}, function (result) {
                    if (xhExtra.checkError(result)) return false;
                    xhExtra.backToList($this.dataGrid);
                    $this.dom.school.change();
                });
            });
            //修改
            $('#bt_form_edit').click(function() {
                $this.form.submit(baseUrl + 'Device/modifyRegister', {}, function (result) {
                    if (xhExtra.checkError(result)) return false;
                    xhExtra.backToList($this.dataGrid);
                });
            });
            //返回
            $('#bt_form_back').click(function () {
                xhExtra.backToList();
            });
            //重置
            $('#bt_form_reset').click(function () {
                $this.form.reset();
            });
            //领用
            $('#bt_list_start_receive').click(function () {
                if (xhExtra.buttonDisabled($(this))) return false;
                $this.funObj().showReceiveQR();
            });
            //更改学校
            $('#bt_list_change_school').click(function () {
                if (xhExtra.buttonDisabled($(this))) return false;
                $this.funObj().changeSchool();
            });
            //同步
            $('#bt_list_syn').click(function () {
                if (xhExtra.buttonDisabled($(this))) return false;
                $this.funObj().synData();
            });
            //设备维修
            $('#bt_list_repair').click(function () {
                if (xhExtra.buttonDisabled($(this))) return false;
                $this.funObj().addRepairApply();
            });

            $("#bt_list_returnTab").click(function () {
                if (xhExtra.buttonDisabled($(this))) return false;
                $this.funObj().returnTab();
            });
            //绑定许可证
            $('#bt_list_bindLicence').click(function () {
                if(xhExtra.buttonDisabled($(this))) return false;
                $this.funObj().bindLicence();
            });
            //查看历史
            $('#bt_list_history').click(function () {
                if(xhExtra.buttonDisabled($(this))) return false;
                $this.funObj().showHistory();
            });
            //设备变更
            $('#bt_list_exchange').click(function () {
                if(xhExtra.buttonDisabled($(this))) return false;
                $this.funObj().exchange();
            });
        },
        funObj: function () {
            var $this = this;
            return {
                bindDataGridEvent: function () {
                    $this.dataGrid.onLoadSuccess = function (data) {
                        if (xhExtra.checkError(data)) return false;
                        if (data.rows.length <= 0) return false;
                        $this.dataGrid.mergeCells(['sDevNumber', 'sMacAddress', 'sReceiverName']);
                    };
                    if ($('#bt_form_edit').length > 0) {
                        $this.dataGrid.onDblClickRow = function (rowIndex, rowData) {
                            if (rowData.iCheck !== '已审核' || isAdmin == 1 ) {
                                xhExtra.ajaxRequest('Device/getRegisterInfo/' + rowData.iUTId, {}, {}, function (data) {
                                    $this.form.reset().fill(data);
                                    $this.dom.school.change();
                                    xhExtra.forwardToForm(true);
                                });
                            } else {
                                window.top.xhTop.showError('已审核，不可修改');
                                return false;
                            }
                        };
                    }
                },
                searchList: function () {
                    $this.dataGrid.reload({
                        search: {
                            items: xhExtra.getValue($('#list_item')),
                            vague: xhExtra.getValue($('#list_vague'))
                        },
                        purpose: xhExtra.getValue($('#list_purpose')),
                        done: xhExtra.getValue($('#list_done')),
                        status: xhExtra.getValue($('#list_status')),
                        school: xhExtra.getValue($('#list_school')),
                        check: xhExtra.getValue($('#list_check')),
                        iCIId:$this.params.iCIId
                    })
                },
                // viewByGroup: function (_target) {
                //     $this.dataGrid.params.group = _target;
                //     $this.funObj().searchList();
                // },
                delRegister: function () {
                    xhExtra.askChangeStatus(
                        'Device/delRegister',
                        {ids: $this.dataGrid.getSelectValues('iUTId')},
                        $this.dataGrid
                    );
                },
                doneRegister: function () {
                    xhExtra.askChangeStatus(
                        'Device/returnRegister',
                        {ids: $this.dataGrid.getSelectValues('iUTId')},
                        $this.dataGrid,
                        '确认归还？'
                    );
                },
                showReceiveQR: function () {
                    var ids = $this.dataGrid.getSelectValues('iUTId');
                    xhExtra.ajaxRequest('Device/receiveRegisterQR', {ids: ids}, {check: true}, function(image) {
                        window.top.swal({
                            title: '领用设备-' + ids.length + '台',
                            // html: '<img src="data:image/png;base64,' + image.msg + '" width="80%">'
                            html: '<img src="' + image.msg + '" width="80%">'
                        });
                    });
                    // window.top.swal({
                    //     title: '领用（' + ids.length + '）台',
                    //     html: '<img src="' + baseUrl + 'Device/receiveRegisterQR?ids=' + ids.join(',') + '" width="100%">'
                    // });
                },
                changeSchool: function () {
                    if (!$this.params.schoolId) {
                        xhExtra.ajaxRequest(
                            'Other/getSchoolPower', {},
                            {success: false, check: true},
                            function (data) {
                                $this.params.schoolId = data;
                                $this.funObj().changeSchool();
                            }
                        );
                        return false;
                    }
                    window.top.swal({
                        title: '修改学校',
                        input: 'select',
                        inputOptions: $this.params.schoolId,
                        inputPlaceholder: '选择学校',
                        inputAttributes: {
                            'class': 'form-control'
                        },
                        showCancelButton: true,
                        confirmButtonText: '确认',
                        cancelButtonText: '取消',
                        showLoaderOnConfirm: true,
                        allowOutsideClick: true,
                        preConfirm: function(schoolId) {
                            return new Promise(function (resolve, reject) {
                                if(!schoolId){
                                    reject('学校为必选！');
                                }
                                else {
                                    xhExtra.ajaxRequest(
                                        'Device/setRegisterSchool',
                                        {ids: $this.dataGrid.getSelectValues('iUTId'), schoolId: schoolId},
                                        {success: true, table: $this.dataGrid}
                                    );
                                    resolve();
                                }
                            })
                        }
                    }).then(function(isConfirm) {}, function(dismiss) {});
                },
                synData: function () {
                    ids = $this.dataGrid.getSelectValues('iUTId');
                    if (ids.length < 1){
                        window.top.xhTop.showError('请选择后操作');
                        return false;
                    }
                    xhExtra.askChangeStatus('Device/synRegister', {ids: ids}, $this.dataGrid, '确认同步'+ids.length+'台设备数据吗？', function(result) {
                        if (result.errorNum !== 0){
                            var content = '';
                            $.each(result.errorData, function(index, row){
                                content += '<tr><td>' + row.sReceiverName + '</td><td>' + row.sReceiverAccount + '</td><td>' + row.sDevNumber + '</td><td>' + row.reason + '</td></tr>';
                            });
                            window.top.swal({
                                title: result.msg,
                                type: 'warning',
                                html: '<table class="table table-striped"><tr>' +
                                '<th style="text-align: center">姓名</th>' +
                                '<th style="text-align: center">领用账号</th>' +
                                '<th style="text-align: center">设备号</th>' +
                                '<th style="text-align: center">原因</th>' +
                                '</tr>' + content + '</table>'
                            });
                        } else {
                            window.top.xhTop.showSuccess(result.msg);
                        }
                    });
                },
                addRepairApply: function () {
                    var id = $this.dataGrid.getSelectValue('iUTId');
                    var sDevNumber = $this.dataGrid.getSelectValue('sDevNumber');
                    var sDevType = $this.dataGrid.getSelectValue('sDevType');
                    var sIMei = $this.dataGrid.getSelectValue('sIMei');
                    if (id < 0 ) {
                        window.top.xhTop.showError('未选中记录！');
                        return false;
                    }
                    if (sDevNumber == null || sDevNumber === ''){
                        window.top.xhTop.showError('设备号为空，请检查数据');
                        return false;
                    }
                    window.top.xhTop.showModal({
                        title: '创建设备维修申请单',
                        content: xhTool.getFrameString('device/showRegisterRepair', {id:id}, 350),
                        button: '保存',
                        size: 'sm',
                        width:'600',
                        backClose: false
                    });
                },
                returnTab:function () {
                    var ids = $this.dataGrid.getSelectValues('iUTId');
                    var schoolIds = $this.dataGrid.getSelectValues('iSchoolId');
                    $.unique(schoolIds);
                    if (schoolIds.length != 1) {
                        window.top.xhTop.showError('错误', '所选的学校>1');
                        return false;
                    }
                    xhExtra.ajaxRequest('device/ajaxGetPlanName',{schoolId:schoolIds[0]},{check:false},function (res) {
                        var html = '';
                        if (res.code != 400 && res.code != 500) {
                            html = '<select id="iBPPId" class="form-control">\n' +
                                '                  <option value=""   style="display: none;">请选择一个流程计划</option>\n';
                            if (res.length > 0) {
                                $.each(res, function (index,item) {
                                    html += '      <option value="'+item['id']+'" ';
                                    html +='>'+item['name']+'</option>\n' ;
                                });
                            }
                            html +='      </select>';
                        }
                        window.top.swal({
                            titleText: '退还申请',
                            html:html + '<br><textarea type="date" class="form-control" id="mDesc" rows="3"></textarea>',
                            showCancelButton: true,
                            cancelButtonText: '取消',
                            confirmButtonText: '确认',
                            showLoaderOnConfirm: true,
                            preConfirm: function () {
                                return new Promise(function (resolve, reject) {
                                    var desc = $('#mDesc' , window.top.document).val();
                                    if (!desc) {
                                        reject('理由必填');
                                    } else {
                                        resolve(desc);
                                    }
                                })
                            },
                            allowOutsideClick: true
                        }).then(function (desc) {
                            var iBPPId = $('#iBPPId',window.top.document).val();
                            xhExtra.ajaxRequest('device/saveReturnTab',{sSourceIds:ids.join(','),mDesc:desc,iSource:1,iBPPId:iBPPId,iSchoolId:schoolIds[0]},null,function (res) {
                                window.top.xhTop.showSuccess(res.msg);
                                $this.dataGrid.reload();
                            });
                        }, function(dismiss) {});
                    });


                //     var ids = $this.dataGrid.getSelectValues('iUTId');
                //     window.top.swal({
                //         titleText: '退还申请',
                //         html:'<textarea type="date" class="form-control" id="mDesc" rows="3"></textarea>',
                //         showCancelButton: true,
                //         cancelButtonText: '取消',
                //         confirmButtonText: '确认',
                //         showLoaderOnConfirm: true,
                //         preConfirm: function () {
                //             return new Promise(function (resolve, reject) {
                //                 var desc = $('#mDesc' , window.top.document).val();
                //                 if (!desc) {
                //                     reject('理由必填！');
                //                 } else {
                //                     resolve(desc);
                //                 }
                //             })
                //         },
                //         allowOutsideClick: true
                //     }).then(function (desc) {
                //         xhExtra.ajaxRequest('device/saveReturnTab',{sSourceIds:ids.join(','),mDesc:desc,iSource:1},null,function (res) {
                //             window.top.xhTop.showSuccess(res.msg);
                //             $this.dataGrid.reload();
                //         });
                //     }, function(dismiss) {});
                },
                bindLicence:function () {
                    var sDeviceNumbers = $this.dataGrid.getSelectValues('sDevNumber');
                    if (!sDeviceNumbers) {
                        window.top.xhTop.showError('未选中学生！');
                    }
                    var url = 'licence/bindLicence?deviceId[]=';
                    var ifNull = 0;
                    $.each(sDeviceNumbers, function(index, value) {
                        if(value){
                            if (index == 0) {
                                url +=  value;
                            } else {
                                url += '&deviceId[]=' + value;
                            }
                        }else{
                            ifNull = 1;
                        }
                    });
                    if (ifNull == 1) {
                        window.top.xhTop.showError('有选中学生设备号为空！');
                        return false;
                    }
                    window.top.xhTop.showModal({
                        title: '绑定许可证',
                        width: 800,
                        content: '<iframe src="' + url + '"  style="width: 100%;border-style: none;padding: 0px;height: 400px"  scrolling="yes"   ></iframe>',
                        backClose: false
                    });
                },
                commData: function (level) {
                    var id = $this.dataGrid.getSelectValues('iUTId');
                    var sDeviceNumber = $this.dataGrid.getSelectValue('sDevNumber');
                    var iUTId = $this.dataGrid.getSelectValue('iUTId');
                    var devType = $this.dataGrid.getSelectValue('sDevType');
                    if (id.length <= 0) {
                        window.top.xhTop.showError('未选中记录！');
                        return false;
                    }
                    if (id.length > 1){
                        window.top.xhTop.showError('请单选后操作');
                        return false;
                    }
                    if (!sDeviceNumber) {
                        window.top.xhTop.showError('没有设备号信息，不可操作');
                        return false;
                    }
                    var url = '';
                    if (level === 1){
                        window.top.xhTop.showModal({
                            title: '填写' + sDeviceNumber + '备注',
                            content: xhTool.getFrameString('Device/addRegisterNoteForm', {device: sDeviceNumber, iUTId: iUTId, devType:devType}, 450),
                            button: '保存',
                            size: 'sm',
                            width:'700',
                            backClose: false
                        });
                    } else {
                        window.top.xhTop.showModal({
                            title: sDeviceNumber + '备注记录',
                            content: xhTool.getFrameString('Device/getNoteMsgList?device='+sDeviceNumber+'&iUTId='+iUTId, {}, $(window).height()-20),
                            size: 'lg',
                            backClose: false
                        });
                    }
                },
                showHistory: function () {
                    var sDeviceNumber = $this.dataGrid.getSelectValue('sDevNumber');
                    if (!sDeviceNumber) {
                        window.top.xhTop.showError('没有设备号不可查看');
                        return false;
                    }
                    window.top.xhTop.showModal({
                        title: '设备 ' + sDeviceNumber + ' 历史数据',
                        content: xhTool.getFrameString('Device/registerHistory', {device:sDeviceNumber}, $(window).height()-20),
                        size: 'lg',
                        backClose: true
                    });
                },
                exchange: function () {
                    var iUTId = $this.dataGrid.getSelectValue('iUTId');
                    var sDeviceNumber = $this.dataGrid.getSelectValue('sDevNumber');
                    var iReceivePurpose = $this.dataGrid.getSelectValue('iReceivePurpose');
                    if (!sDeviceNumber) {
                        window.top.xhTop.showError('没有设备号不变更');
                        return false;
                    }
                    var purpose = $this.funObj().getPurposeStr(iReceivePurpose);
                    window.top.xhTop.showModal({
                        title: purpose + '：' + sDeviceNumber + ' 变更申请',
                        content: xhTool.getFrameString('Device/exchangeDevice', {id:iUTId}, 350),
                        size: 'md',
                        backClose: false
                    });
                },
                getPurposeStr: function (_str) {
                    if (_str.indexOf("教师机") !== -1) {
                        return '教师机';
                    }
                    if (_str.indexOf("自用") !== -1) {
                        return '自用机';
                    }
                    if (_str.indexOf("备用") !== -1) {
                        return '备用机';
                    }
                    if (_str.indexOf("学校公用") !== -1) {
                        return '公用机';
                    }
                }
            }
        }
    }
}